package com.apes.framework.plugin.filereader.xml;

import com.apes.framework.api.ApesParser;
import org.springframework.util.Assert;

import java.util.*;

/**
 * 功能：节点元素实现类
 *
 * @author xul
 * @create 2018-04-16 13:32
 */
public class SimpleApesElement implements ApesElement {

    private String name;
    private ApesElement parent;
    private ApesParser parser;
    private String text;
    private final List<ApesElement> nestedElements = new LinkedList();
    private final Map<String, String> attributes = new HashMap<>();

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void setText(String text) {
        this.text = text;
    }

    @Override
    public String getText() {
        return this.text;
    }

    @Override
    public void setParent(ApesElement parent) {
        this.parent = parent;
    }

    @Override
    public ApesElement getParent() {
        return parent;
    }

    @Override
    public void setAttribute(String key, String value) {
        Assert.notNull(key, "key must not be null");
        this.attributes.put(key, value);
    }

    /**
     * 功能：获取指定属性
     */
    @Override
    public String getAttribute(String key) {
        return this.attributes.get(key);
    }

    /**
     * 功能：获取所有属性
     */
    @Override
    public Map<String, String> getAttributes() {
        return this.attributes;
    }

    @Override
    public void setNestedElement(ApesElement element) {
        Assert.notNull(element, "ApesElement must not be null");
        this.nestedElements.add(element);
    }

    /**
     * 功能：获取所有子节点
     */
    @Override
    public Collection<ApesElement> getNestedElements() {
        return this.nestedElements;
    }

    @Override
    public void setParser(ApesParser parser) {
        this.parser = parser;
    }


    @Override
    public <T> T parse() {
        if (parser == null) throw new RuntimeException("节点：" + this.getName() + "没有设置解析器！");
        return (T) parser.parse(this);
    }
}
